import React, { useState } from "react";
import './index.less';
import { Input, Button, message } from 'antd';
import {
  UserOutlined,
  EyeTwoTone,
  EyeInvisibleOutlined
} from '@ant-design/icons';
import { request } from '@apis/request';
import { useNavigate } from "react-router-dom";

const Login = () => {

  const navigate = useNavigate();
  const [userName, setUserName] = useState('');
  const [password, setPassword] = useState('');

  const login = async () => {
    if (userName !== 'admin') {
      message.error('非管理员身份，登录失败！');
      return;
    }
    const res = await request('/getUserInfo', { userName, password });
    if (res.code === '0000') {
      navigate('/', { replace: true });
      localStorage.setItem('userInfo', JSON.stringify(res.data));
    } else {
      const re = await request('/login', { userName, password }, 'post');
      if (re.code === '0000') {
        message.success('登录成功');
        navigate('/', { replace: true });
        localStorage.setItem('userInfo', JSON.stringify(re.data))
      } else {
        message.error(re.message);
      }
    }
  }

  return <div className="login">
    <div className="login_main">
      <Input className="user_name" placeholder="用户名"
        prefix={<UserOutlined />}
        value={userName}
        onChange={e => {setUserName(e.target.value)}}
      />
      <Input.Password className="psd" placeholder="密码"
        iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
        value={password}
        onChange={e => {setPassword(e.target.value)}}
      />
      <Button className="login_btn"
        onClick={login}
      >登录</Button>
    </div>
  </div>
}

export default Login;